package com.kerrykidz.system.util.sync;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.lang3.SerializationUtils;

public class SerializableHelper {

	/**
	 * 序列化文件路径
	 */
	private static String dicPath = null;

	/**
	 * 
	 * @Desc 获取序列化目录
	 * @author QUINN
	 * @date 2014年9月9日下午8:19:58
	 * @return
	 */
	private static String getDicPath() {
		if (dicPath == null)
			if (OsUtils.isLinux())
				dicPath = "var\\kerrykidz\\serialize\\";
			else if (OsUtils.isWindows())
				dicPath = "c:\\kerrykidz\\serialize\\";
		File dic = new File(dicPath);
		if (!dic.exists())
			dic.mkdirs();
		return dicPath;
	}

	/**
	 * 
	 * @Desc 序列化对象
	 * @author QUINN
	 * @date 2014年9月9日下午8:12:59
	 * @param o
	 * @return
	 */
	public static void serialize(MessageTask task) {

		byte bytes[] = SerializationUtils.serialize(task);
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		File fil = new File(getDicPath() + task.getTaskId());
		try {
			OutputStream os = new FileOutputStream(fil);
			os.write(bytes);
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Desc 反序列化
	 * @author QUINN
	 * @date 2014年9月9日下午8:26:28
	 * @param fileName
	 * @return
	 */
	public static MessageTask deserialize(String serializeId) {
		File fil = new File(getDicPath() + serializeId);
		try {
			InputStream is = new FileInputStream(fil);
			byte[] bytes = new byte[is.available()];
			is.read(bytes);
			is.close();
			return  (MessageTask) SerializationUtils.deserialize(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @Desc 删除序列文件
	 * @author QUINN
	 * @date 2014年9月9日下午8:32:41
	 * @param fileName
	 * @return
	 */
	public static boolean removeSeriaFile(String serializeId) {
		File fil = new File(getDicPath() + serializeId);
		return fil.exists() && fil.delete();
	}

	public static void main(String[] args) {
		System.out.println(removeSeriaFile("1410265799104"));
	}
}
